#include <iostream>
#include <functional>

using std::cout;
using std::endl;
using std::bind;
using std::function;

int add(int x, int y)
{
    cout << "int add(int, int)" << endl;
    return x + y;
}

int multiply(int x, int y, int z)
{
    cout << "int multiply(int, int, int)" << endl;
    return x * y * z;
}

class Example
{
public:
    //Example * this
    int add(int x, int y)
    {
        cout << "int Example::add(int, int)" << endl;
        return x + y;
    }

    int data = 100;//C++11中提出来的，可以在声明数据成员的时候
                   //进行初始化
};

void test()
{
    //函数的类型（标签）:函数的返回类型与函数的参数列表（函数的
    //参数的个数、参数的类型、参数的顺序）
    //add函数的类型:int(int, int)
    //bind改变了add函数的类型，变为了int()
    //因为function可以存放函数类型，将其称为函数的容器
    /* auto f = bind(&add, 1, 2); */
    function<int()> f = bind(&add, 1, 2);
    cout << "f() = " << f() << endl;

    cout << endl;
    //multiply的函数类型：int(int, int, int)
    //f2的类型int()
    function<int()> f2 = bind(multiply, 3, 4, 5);
    cout << "f2() = " << f2() << endl;

    cout << endl;
    Example ex;
    //Example中的add函数的函数类型:int(Example *, int, int)
    //f3的类型:int()
    function<int()> f3 = bind(&Example::add, &ex, 100, 200);
    cout << "f3() = " << f3() << endl;

    cout << endl;
    //占位符
    using namespace std::placeholders;
    //add函数的类型：int(int, int)
    //f4的类型：int(int)
    function<int(int)> f4 = bind(add, 100, _1);
    cout << "f4(300) = " << f4(300) << endl;

    cout << endl;
    function<int()> f5 = bind(&Example::data, &ex);
    cout << "f5() = " << f5() << endl;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

